import React, { useState, useEffect } from 'react';
import InputField from './InputField.jsx';
import ResultDisplay from './ResultDisplay.jsx';
import PensionByYearsChart from '../chart/PensionByYearsChart.jsx';
import PensionBySalaryChart from '../chart/PensionBySalaryChart.jsx';
import BreakEvenPointChart from '../chart/BreakEvenPointChart.jsx';
import BreakEvenPointBySalaryChart from '../chart/BreakEvenPointBySalaryChart.jsx';
import BreakEvenPointByLocalSalaryChart from '../chart/BreakEvenPointByLocalSalaryChart.jsx';
import * as PensionCalc from '../utils/pensionCalculations.js';

/**
 * 养老金计算器组件
 * @returns {JSX.Element}
 */
const PensionCalculator = () => {
  const [params, setParams] = useState({
    employmentType: 'employee', // 就业类型：employee(在职) 或 freelancer(灵活就业)
    currentSalary: 10000, // 当前税前工资
    localAverageSalary: 9000, // 当地上年度在岗职工月平均工资
    contributionYears: 25, // 缴费年限
    retirementAge: 60, // 退休年龄
    baseRate: 1 // 灵活就业基准比例，默认为100%
  });

  const [results, setResults] = useState({
    basicPension: 0,
    personalAccountPension: 0,
    monthlyPension: 0,
    totalContribution: 0,
    breakEvenPoint: 0,
    personalIndexedSalary: 0
  });

  // 处理输入变化
  const handleInputChange = (e) => {
    const { name, value, type } = e.target;
    let parsedValue = type === 'number' ? parseFloat(value) : value;
    
    // 特殊处理基准比例选择
    if (name === 'baseRateOption') {
      const baseRateMap = {
        '60': 0.6,
        '70': 0.7,
        '80': 0.8,
        '90': 0.9,
        '100': 1,
        '150': 1.5,
        '200': 2,
        '250': 2.5,
        '300': 3
      };
      setParams({
        ...params,
        baseRate: baseRateMap[value]
      });
      return;
    }
    
    setParams({
      ...params,
      [name]: parsedValue
    });
  };

  // 当参数变化时，重新计算结果
  useEffect(() => {
    calculatePension();
  }, [params]);

  // 计算养老金
  const calculatePension = () => {
    const { 
      employmentType, 
      currentSalary, 
      localAverageSalary, 
      contributionYears, 
      retirementAge,
      baseRate
    } = params;
    
    const payoutMonths = PensionCalc.getPayoutMonths(retirementAge);
    let personalIndexedSalary, personalAccountTotal, totalContribution;
    
    // 针对不同就业类型计算
    if (employmentType === 'employee') {
      // 在职人员
      const contributionIndex = PensionCalc.calculateContributionIndex(currentSalary, localAverageSalary);
      personalIndexedSalary = PensionCalc.calculatePersonalIndexedSalary(localAverageSalary, contributionIndex);
      
      // 限制计算缴费基数在60%-300%之间
      const limitedSalary = Math.max(localAverageSalary * 0.6, Math.min(localAverageSalary * 3, currentSalary));
      personalAccountTotal = PensionCalc.calculateEmployeePAT(limitedSalary, 0.08, contributionYears);
      totalContribution = PensionCalc.calculateEmployeeTotalContribution(limitedSalary, 0.08, contributionYears);
    } else {
      // 灵活就业人员
      personalIndexedSalary = PensionCalc.calculatePersonalIndexedSalary(localAverageSalary, baseRate);
      personalAccountTotal = PensionCalc.calculateFreelancerPAT(localAverageSalary, baseRate, contributionYears);
      totalContribution = PensionCalc.calculateFreelancerTotalContribution(localAverageSalary, baseRate, contributionYears);
    }
    
    // 计算养老金
    const basicPension = PensionCalc.calculateBasicPension(localAverageSalary, personalIndexedSalary, contributionYears);
    const personalAccountPension = PensionCalc.calculatePersonalAccountPension(personalAccountTotal, payoutMonths);
    const monthlyPension = PensionCalc.calculateMonthlyPension(basicPension, personalAccountPension);
    
    // 计算收支平衡点
    const breakEvenPoint = PensionCalc.findBreakEvenPoint(totalContribution, monthlyPension);
    
    setResults({
      basicPension,
      personalAccountPension,
      monthlyPension,
      totalContribution,
      breakEvenPoint,
      personalIndexedSalary
    });
  };

  return (
    <div className="pension-calculator">
      <div className="calculator-header">
        <h2>养老金计算器</h2>
        <p>根据国家养老金计算公式，计算您的养老金及相关指标</p>
      </div>
      
      <div className="calculator-form">
        <div className="form-section">
          <h3>基本参数</h3>
          
          <div className="employment-type-selector">
            <span>就业类型：</span>
            <label>
              <input 
                type="radio" 
                name="employmentType" 
                value="employee" 
                checked={params.employmentType === 'employee'} 
                onChange={handleInputChange} 
              />
              在职人员
            </label>
            <label>
              <input 
                type="radio" 
                name="employmentType" 
                value="freelancer" 
                checked={params.employmentType === 'freelancer'} 
                onChange={handleInputChange} 
              />
              灵活就业人员
            </label>
          </div>
          
          <InputField 
            label="当地上年度在岗职工月平均工资" 
            name="localAverageSalary" 
            value={params.localAverageSalary}
            onChange={handleInputChange}
            type="number"
            unit="元/月"
            min={1000}
            step={100}
          />
          
          <InputField 
            label="缴费年限" 
            name="contributionYears" 
            value={params.contributionYears}
            onChange={handleInputChange}
            type="number"
            unit="年"
            min={15}
            max={50}
            step={0.5}
          />
          
          <InputField 
            label="退休年龄" 
            name="retirementAge" 
            value={params.retirementAge}
            onChange={handleInputChange}
            type="number"
            unit="岁"
            min={50}
            max={60}
            step={10}
          />
          
          {params.employmentType === 'employee' ? (
            <InputField 
              label="当前税前工资" 
              name="currentSalary" 
              value={params.currentSalary}
              onChange={handleInputChange}
              type="number"
              unit="元/月"
              min={0}
              step={100}
            />
          ) : (
            <div className="input-field">
              <label>基准比例</label>
              <select 
                name="baseRateOption" 
                value={params.baseRate * 100} 
                onChange={handleInputChange}
              >
                <option value="60">60%（最低档）</option>
                <option value="70">70%</option>
                <option value="80">80%</option>
                <option value="90">90%</option>
                <option value="100">100%（参考档）</option>
                <option value="150">150%</option>
                <option value="200">200%</option>
                <option value="250">250%</option>
                <option value="300">300%（最高档）</option>
              </select>
              <div className="input-note">
                基准金额：{(params.localAverageSalary * params.baseRate).toFixed(2)}元/月
              </div>
              <div className="input-note">
                月缴费金额：{(params.localAverageSalary * params.baseRate * 0.2).toFixed(2)}元/月
              </div>
            </div>
          )}
        </div>
        
        <ResultDisplay results={results} params={params} />
      </div>
      
      <div className="charts-container">
        <BreakEvenPointChart 
          currentSalary={params.currentSalary}
          contributionYears={params.contributionYears}
          localAverageSalary={params.localAverageSalary}
          retirementAge={params.retirementAge}
          employmentType={params.employmentType}
          baseRate={params.baseRate}
        />
        
        <PensionByYearsChart 
          currentSalary={params.currentSalary}
          localAverageSalary={params.localAverageSalary}
          retirementAge={params.retirementAge}
          employmentType={params.employmentType}
          baseRate={params.baseRate}
        />
        
        <PensionBySalaryChart 
          contributionYears={params.contributionYears}
          localAverageSalary={params.localAverageSalary}
          retirementAge={params.retirementAge}
          employmentType={params.employmentType}
          baseRate={params.baseRate}
        />
        
        <BreakEvenPointBySalaryChart 
          contributionYears={params.contributionYears}
          localAverageSalary={params.localAverageSalary}
          retirementAge={params.retirementAge}
          employmentType={params.employmentType}
          baseRate={params.baseRate}
        />
        
        <BreakEvenPointByLocalSalaryChart 
          currentSalary={params.currentSalary}
          contributionYears={params.contributionYears}
          localAverageSalary={params.localAverageSalary}
          retirementAge={params.retirementAge}
          employmentType={params.employmentType}
          baseRate={params.baseRate}
        />
      </div>
    </div>
  );
};

export default PensionCalculator; 